package permission

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/samber/lo"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminrole"
	"private-domain-overseas-service/tools/ent/adminuser"
	"private-domain-overseas-service/tools/ent/adminuserrole"
	"private-domain-overseas-service/tools/ent/predicate"
	"strconv"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminUserSmsLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminUserSmsLoginLogic - 验证码登录
func NewAdminUserSmsLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserSmsLoginLogic {
	return &AdminUserSmsLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminUserSmsLoginLogic) AdminUserSmsLogin(req *types.AdminSmsCaptchaLoginRequest) (resp *types.AdminSmsCaptchaLoginResponse, err error) {
	userDao := permission.NewAdminUserDao(l.ctx, l.svcCtx)
	adminRoleDAO := permission.NewAdminRoleDao(l.ctx, l.svcCtx)
	adminUserRoleDAO := permission.NewAdminUserRoleDao(l.ctx, l.svcCtx)

	// 查询管理员账号
	cond := make([]predicate.AdminUser, 0, 2)
	cond = append(cond, adminuser.AdminUserUsernameEQ(req.Phone))
	adminUser, _ := userDao.AdminUserFirst(cond)
	if adminUser == nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerAdminUserNotExist, "用户不存在")
	}

	// 用户名存在，但是已被删除
	if adminUser.IsDelete != bizadmin.NotDelete {
		adminUser.IsDelete = bizadmin.NotDelete
		adminUser.AdminUserStatus = bizadmin.StatusDisable
		_ = userDao.AdminUserUpdate(adminUser, nil)
		return nil, xerr.ErrCodeMsg(xerr.ServerAdminAccountDeleted, "用户已被删除")
	}

	// 校验用户
	if adminUser.AdminUserStatus == bizadmin.StatusDisable {
		return nil, xerr.ErrCodeMsg(xerr.ServerAdminAccountBanned, "用户已被禁用")
	}

	// 从redis校验验证码
	err = handleCheckCaptchaFromRedis(l.svcCtx.BizRedis, l.ctx, constant.HzAdminLoginCaptchaKey+req.Phone, req.Captcha)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerAdminSMSCodeError, fmt.Sprintf("验证码校验失败，%v", err.Error()))
	}

	// 根据用户id查角色
	userConditions := make([]predicate.AdminUserRole, 0, 1)
	userConditions = append(userConditions, adminuserrole.AdminUserRoleUserIDEQ(int64(adminUser.ID)))
	adminUserRoles, err := adminUserRoleDAO.UserRoleConditionsAll(userConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("获取用户角色失败: %v", err.Error()))
	}

	// 序列化角色id（角色id）
	roleIds := lo.Map(adminUserRoles, func(item *ent.AdminUserRole, _ int) int {
		return int(item.AdminUserRoleRoleID)
	})
	marshalRoleIds, _ := json.Marshal(roleIds)

	// 根据角色id查角色
	roleConditions := make([]predicate.AdminRole, 0, 1)
	roleConditions = append(roleConditions, adminrole.IDIn(roleIds...))
	adminRoles, err := adminRoleDAO.AdminRoleConditionsAll(roleConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("获取用户角色失败: %v", err.Error()))
	}

	// 从角色中取出按钮id
	buttonOriginIds := lo.Map(adminRoles, func(item *ent.AdminRole, _ int) []int {
		return lo.Map(strings.Split(item.AdminRoleRouterIds, ","), func(item string, _ int) int {
			id, _ := strconv.Atoi(item)
			return id
		})
	})

	// 序列化按钮id（按钮id）
	allButtonIds := lo.Flatten(buttonOriginIds)
	buttonIds := lo.Uniq(allButtonIds)
	marshalButtonIds, _ := json.Marshal(buttonIds)

	//生成token
	accessSecret := l.svcCtx.Config.Auth.AccessSecret
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	//生成token
	token, err := common.JwtAdminCreate(accessSecret, accessExpire, fmt.Sprint(adminUser.ID), string(marshalRoleIds), string(marshalButtonIds))
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("生成token失败: %v", err.Error()))
	}
	// 生成rememberToken，7天过期
	rememberToken, err := common.JwtAdminCreate(accessSecret, 60*60*24*7, strconv.Itoa(adminUser.ID), string(marshalRoleIds), string(marshalButtonIds))
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("生成token失败: %v", err.Error()))
	}

	// 返回token
	return &types.AdminSmsCaptchaLoginResponse{
		Token:         token,
		RememberToken: rememberToken,
	}, nil
}

// handleCheckCaptchaFromRedis - 从redis检查短信验证码
func handleCheckCaptchaFromRedis(redisClient *redis.Redis, ctx context.Context, redisKey, originCaptcha string) error {
	//从redis中获取验证码
	captcha, err := redisClient.GetCtx(ctx, redisKey)
	if err != nil {
		return errors.New(fmt.Sprintf("获取验证码失败：%v", err.Error()))
	}

	//校验验证码
	if captcha == "" || captcha != originCaptcha {
		return errors.New("验证码不正确")
	}

	// 删除验证码
	_, err = redisClient.DelCtx(ctx, redisKey)
	if err != nil {
		return errors.New(fmt.Sprintf("删除验证码失败：%v", err.Error()))
	}

	return nil
}
